package com.fc.im.netty.codec;

import com.fc.im.netty.message.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.nio.ByteBuffer;

/**
 * Created by ChanJiabo on 2017/1/18.
 */
public class MessageEncoder extends MessageToByteEncoder<Message> {

    private static final byte FIRST_FLAG = 0x66;
    private static final byte SECOND_FLAG = 0x63;
    private static final byte[] FLAGS = {FIRST_FLAG, SECOND_FLAG};

    @Override
    protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception {
        if (msg == null) {
            return;
        }
        try{
            out.writeBytes(FLAGS);
            ByteBuffer byteBuffer = msg.build();
            out.writeBytes(byteBuffer);
            byte[] body = msg.getBody();
            if (body != null) {
                out.writeBytes(body);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
